package com.fingerth.crawler.ui.fragment

import android.annotation.SuppressLint
import android.view.View
import com.fingerth.crawler.R
import com.fingerth.crawler.base.BaseFrag
import com.fingerth.crawler.bean.NovelChapterListBean
import com.fingerth.crawler.bean.NovelContentBean
import com.fingerth.crawler.bean.NovelListBean
import com.fingerth.crawler.databinding.FragmentNovelCrawlerBinding
import com.fingerth.crawler.net.retrofit.NetworkUtils
import com.fingerth.crawler.room.NovelChapter
import com.fingerth.crawler.room.NovelChapterDaoUtils
import com.fingerth.crawler.room.NovelCollectionDaoUtils
import com.fingerth.crawler.utils.AppConstants
import com.fingerth.crawler.utils.SBarUtils
import com.fingerth.crawler.utils.stati.L
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class CrawlerNovelFragment : BaseFrag<FragmentNovelCrawlerBinding>(), View.OnClickListener {

    /**
     * 1.小说搜索
     *      GET  http://api.pingcc.cn/fiction/search/{option}/{key}/{from}/{size}
     * 2.接口描述
     *      例子：http://api.pingcc.cn/fiction/search/fictionType/%E9%83%BD%E5%B8%82/1/30
     * 3.请求参数
     *      参数名     参数类型            描述
     *      option     字符串       选择搜索项，标题：title ， 作者 ：author ，分类：fictionType
     *      key        字符串          搜索关键字
     *      from       整数          当前页数，留空默认1
     *      size       整数      一页显示的数量，留空默认10，最多100
     * 4.分类列表
     *      都市 穿越 科幻 网游 玄幻 修真 言情 历史 其他 竞技
     */

    /**
     * 1.小说章节
     *      GET  http://api.pingcc.cn/fictionChapter/search/{fictionId}
     * 2.接口描述
     *      例子：http://api.pingcc.cn/fictionChapter/search/11602
     * 3.请求参数
     *      参数名      参数类型            描述
     *      fictionId   字符串    通过小说搜索API获取到fictionId
     */

    /**
     * 1.小说内容
     *      GET  http://api.pingcc.cn/fictionContent/search/{chapterId}
     * 2.接口描述
     *      例子：http://api.pingcc.cn/fictionContent/search/11194558
     * 3.请求参数
     *      参数名      参数类型            描述
     *      chapterId   字符串    通过小说章节API获取chapterId
     */

    private val daoUtils: NovelCollectionDaoUtils by lazy { NovelCollectionDaoUtils() }
    private val daoChapterUtils: NovelChapterDaoUtils by lazy { NovelChapterDaoUtils() }
    private var index = 1
    private var isEnd = false
    override fun initData() {
        SBarUtils().setBarHeight(vBinding.barView)
        vBinding.loadNovelBookBt.setOnClickListener(this)
        vBinding.loadNovelChapterBt.setOnClickListener(this)
        vBinding.loadNovelContentBt.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.load_novel_book_bt -> onGetNovelBookByType()
            R.id.load_novel_chapter_bt -> onGetNovelChapter()
            R.id.load_novel_content_bt -> onGetNovelChapterContent()
        }
    }

    private fun percentage(a: Int, b: Int): String {
        return "${(a * 100 / b).coerceAtMost(100)}%"
    }

    @SuppressLint("SetTextI18n")
    private fun onGetNovelChapterContent() {
        vBinding.loadNovelContentBt.isClickable = false
        launch(Dispatchers.Main) {
            val count = daoChapterUtils.count()
            repeat(count) { offSet ->
                val content = daoChapterUtils.queryByIndex(offSet)
                val nBean = withContext(Dispatchers.IO) {
                    Thread.sleep(2000)
                    content?.let { c -> loadChapterContent(c.chapterId) }
                }
                daoChapterUtils.insertContent(content,nBean)
                vBinding.loadNovelContentTv.text = "${offSet + 1}/${count}"
            }

            vBinding.loadNovelContentTv.text = "加载完成"
            vBinding.loadNovelContentBt.isClickable = true
        }

    }


    @SuppressLint("SetTextI18n")
    private fun onGetNovelChapter() {
        vBinding.loadNovelChapterBt.isClickable = false
        launch(Dispatchers.Main) {
            val count = daoUtils.count()
            repeat(count) { offSet ->
                val nBean = withContext(Dispatchers.IO) {
                    Thread.sleep(2000)
                    daoUtils.queryByIndex(offSet)?.let { loadChapter(it.fictionId) }
                }
                daoChapterUtils.insert(nBean)
                vBinding.loadNovelChapterTv.text = "${offSet + 1}/${count}"
            }

            vBinding.loadNovelBookTv.text = "加载完成"
            vBinding.loadNovelChapterBt.isClickable = true
        }

    }


    @SuppressLint("SetTextI18n")
    private fun onGetNovelBookByType() {
        vBinding.loadNovelBookBt.isClickable = false
        launch(Dispatchers.Main) {
//            repeat(AppConstants.titles.size) {
            repeat(1) {
                vBinding.loadNovelBookTv.text = "${it + 1}/${AppConstants.titles.size} - " + AppConstants.titles[it]
                isEnd = false
                while (!isEnd) {
                    val nBean = withContext(Dispatchers.IO) {
                        Thread.sleep(1500)
                        loadNovel(AppConstants.titles[it], index)
                    }
                    if (nBean?.data?.data != null && nBean.data.data.size > 0) {
                        val repeatSize = daoUtils.insert(nBean)
                        if (repeatSize > 10 && daoUtils.countByType(AppConstants.titles[it]) == nBean.data.count) {
                            index = 1
                            isEnd = true
                        } else index++
                        vBinding.loadNovelBookTv.text = "${it + 1}/${AppConstants.titles.size} - " + AppConstants.titles[it] + " -- " + percentage(index * 100, nBean.data.count)

                        //TODO
                        index = 1
                        isEnd = true
                    } else {
                        index = 1
                        isEnd = true
                    }
                }
            }
            vBinding.loadNovelBookBt.isClickable = true
            vBinding.loadNovelBookTv.text = "加载完成，总共${daoUtils.count()}条"
        }

    }


    private suspend fun loadNovel(key: String, index: Int): NovelListBean? {
        return suspendCoroutine { continuation ->
            val response = NetworkUtils.httpService3.onGetNovelList("fictionType", key, index, 10).execute()
            continuation.resume(response.body())
        }
    }

    private suspend fun loadChapter(fictionId: String): NovelChapterListBean? {
        return suspendCoroutine { continuation ->
            val response = NetworkUtils.httpService3.onGetNovelChapterList(fictionId).execute()
            continuation.resume(response.body())
        }
    }

    private suspend fun loadChapterContent(chapterId: String): NovelContentBean? {
        return suspendCoroutine { continuation ->
            val response = NetworkUtils.httpService3.onGetNovelChapterContent(chapterId).execute()
            continuation.resume(response.body())
        }
    }


}